package com.xqboss.chain.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.reddate.wuhanddc.dto.ddc.Account;
import com.xqboss.chain.domain.chain.SysUserChain;
import com.xqboss.chain.echain.EChainSDK;
import com.xqboss.chain.mapper.SysUserChainMapper;
import com.xqboss.common.core.redis.lock.LockValue;
import com.xqboss.common.core.redis.lock.RedisLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author Trent
 * @date 2023/8/11
 */
@Service
public class SysUserChainService extends ServiceImpl<SysUserChainMapper, SysUserChain> {

    @Autowired
    private BsnService bsnService;

    //创建用户区块链地址
    private SysUserChain initUserChain(Long userId){
        EChainSDK sdk = new EChainSDK();
        com.xqboss.chain.echain.Account account = sdk.generateAccount();
//        Account account = bsnService.createAccount();
        SysUserChain sysUserChain = new SysUserChain();
        sysUserChain.setUserId(userId);
        sysUserChain.setAddress(account.getAddress());
//        sysUserChain.setPublicKey(account.publicKey);
        sysUserChain.setPrivateKey(account.getPrivateKey());
//        sysUserChain.setMnemonic(account.mnemonic);
        sysUserChain.setUpChain(false);
        save(sysUserChain);
        return sysUserChain;
    }


    /**
     * 获取或者初始化用户钱包
     *
     * @return
     */
    @RedisLock(lockKey = "initUserWallet")
    public SysUserChain getOrInitUserChain(@LockValue Long userId){
        SysUserChain userChain = getById(userId);
        if(Objects.isNull(userChain)){
            userChain = initUserChain(userId);
        }
        return userChain;
    }
}
